#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2010-11-9

@author: zarra
'''
from common import Question, amplitude_plot, image2matrix, matrix2image
from dct import dct2d,idct2d
import cv

class Q6(Question):
    def __init__(self,image,m='show'):
        super(self.__class__,self).__init__('Q6',image,m)
        
    def action(self):
        image = self.image
        
        #opencv的DCT变化
        src  = cv.CreateMat(image.height, image.width, cv.CV_32FC1)
        dst  = cv.CreateMat(image.height, image.width, cv.CV_32FC1)
        
        cv.Convert(image, src)
        cv.DCT(src, dst, cv.CV_DXT_FORWARD)
        
        dst_image =   cv.CreateImage((image.height, image.width), cv.IPL_DEPTH_8U, 1)
        
        cv.Convert(dst,dst_image)
        
        self.display(dst_image, 'DCT_AMP_OPENCV')
        
        #自己实现的DCT变换
        m=image2matrix(image)
        m_dct = dct2d(m)
        
        m_img_dct =  cv.CreateImage((image.width,image.height), image.depth, image.channels)
        for i in range(image.height):
            for j in range(image.width): 
                m_img_dct[i,j] = m_dct[i,j]/256
        #丢弃3/4的DCT信息,仅保留右下角的1/4        
        for i in range(image.height):
            for j in range(image.width): 
                if i<= image.height /2 or j<= image.width/2:
                    m_dct[i,j] = 0
        #反变换        
        m_idct = idct2d(m_dct)

        m_img = matrix2image(m_idct) 
        self.display(m_img_dct, 'DCT_AMP')           
        self.display(m_img, 'DCT_Compression')
        
        diff =  cv.CreateImage((image.width,image.height), image.depth, image.channels)
        
        #计算和原图形的差图像
        for i in range(image.height):
            for j in range(image.width): 
                
                    diff[i,j] = abs(image[i,j]-m_img[i,j])
                    
        self.display(diff, 'difference')
        
if __name__ == '__main__':
    q=Q6('fig5.jpg','save')
    q()
